<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Setting_m extends Base_model {
	public $primary_key = 'setting_id';
	public $_table = 'setting';
	public $config_file = '';

	function __construct() {
        parent::__construct();
        $this->config_file = APPPATH.'config/site_config.php';
    }
	/**
	 * @param string $key
	 * @param string $value
	 * @param bool $delete
	 * @desc get/set cms configuration value. if delete == TRUE, then the key will be deleted
	 */
	function cms_config($key, $value = NULL, $delete = FALSE, $file_name = FALSE){
		if(!$file_name)
			$file_name = $this->config_file;

		if(!file_exists($file_name)) {
			$str= "<?php\n\n";
			$str.= "if (!defined('BASEPATH'))\n";
			$str.= "exit('No direct script access allowed');\n\n";
			@file_put_contents($file_name, $str);
			@chmod($file_name,0777);
		}
		$pattern = array();
		$pattern[] = '/(\$config\[(\'|")'.$key.'(\'|")\] *= *")(.*?)(";)/si';
		$pattern[] = "/(".'\$'."config\[('|\")".$key."('|\")\] *= *')(.*?)(';)/si";

		if($delete){
			$replacement = '';
			$str = file_get_contents($file_name);
			$str = preg_replace($pattern, $replacement, $str);
			@chmod($file_name,0777);
			if(strpos($str, '<?php') !== FALSE && strpos($str, '$config') !== FALSE){
				@file_put_contents($file_name, $str);
				// @chmod($file_name,0555);
			}
			return FALSE;
		}else{
			if($value === NULL){

            // enforce refresh
				if(function_exists('opcache_invalidate')){
					opcache_invalidate($file_name);
				}
				include($file_name);

				if(!isset($config)){
					$config = array();
				}
				if(key_exists($key, $config)){
					$value = $config[$key];
				}else{
					$value = '';
				}
				return $value;
			}else{
				$str = file_get_contents($file_name);
				$replacement = '${1}'.addslashes($value).'${5}';
				$found = FALSE;
				foreach($pattern as $single_pattern){
					if(preg_match($single_pattern,$str)){
						$found = TRUE;
						break;
					}
				}
				if(!$found){
					$str .= PHP_EOL.'$config[\''.$key.'\'] = \''.addslashes($value).'\';';
				}
				else{
					$str = preg_replace($pattern, $replacement, $str);
				}
				@chmod($file_name,0777);
				if(strpos($str, '<?php') !== FALSE && strpos($str, '$config') !== FALSE){
					@file_put_contents($file_name, $str, LOCK_EX);
					// @chmod($file_name,0555);
				}
				return $value;
			}
		}
	}

}
